import msgpack from 'msgpack-js'
import tf from './tf'
/**
 * 解析msgpack bin
 * @param url 文件地址
 */
export async function loadMsgpackJson(url: string) {
  const json = await fetch(url)
    .then((res) => res.arrayBuffer())
    .then((buffer) => {
      const data = new Uint8Array(buffer)
      return msgpack.decode(data)
    })
  return json
}
export async function downloadJsonMsgpack(object: Object, name = 'data.bin') {
  const u8Array = msgpack.encode(object)
  console.log(u8Array)

  const blob = new Blob([u8Array], { type: 'application/octet-stream' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = name
  link.click()
}
export function getLayersModelMemory(model: tf.LayersModel) {
  let internalMemory = 0
  model.layers.forEach((layer) => {
    layer.getWeights().forEach((weight) => {
      internalMemory += weight.size * (weight.dtype === 'float32' ? 4 : 1)
    })
  })
  const totalMemory = internalMemory
  return totalMemory
}

export async function getColorU8ArrayFromTensor(data: tf.Tensor3D) {
  let arr = new Uint8ClampedArray(data.shape[0] * data.shape[1] * data.shape[2])
  const array = await data.data()
  if (data.dtype == 'int32') {
    array.forEach((value, index) => (arr[index] = value))
  } else {
    array.forEach((value, index) => (arr[index] = value * 255))
  }
  return arr
}
export function getUint8ArrayFromTensor(data: tf.Tensor3D) {
  let arr = new Uint8Array(data.shape[0] * data.shape[1] * data.shape[2])
  if (data.dtype == 'int32') {
    data.dataSync().forEach((value, index) => (arr[index] = value))
  } else {
    data.dataSync().forEach((value, index) => (arr[index] = value * 255))
  }
  return arr
}
export function uuid() {
  return (
    Math.random().toString(36).substring(2, 15) +
    Math.random().toString(36).substring(2, 15)
  )
}
